package com.kzw.oa.system.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.system.model.Dictionary;

@Service
@Transactional
public class DictionaryService extends DefaultEntityManager<Dictionary, Long> {


	@Transactional(readOnly = true)
	public List<String> getAllByItemName(final String itemName) {
		String hql = "select itemValue from Dictionary where leaf=1 and itemName=?";
		return findByHQL(hql, itemName);
	}

	@Transactional(readOnly = true)
	public List<Dictionary> getByItemName(final String itemName) {
		String hql = "from Dictionary where leaf=1 and itemName=? order by sn asc";
		return findByHQL(hql, itemName);
	}

	@Transactional(readOnly = true)
	public List<String> getAllItems() {
		String hql = "select itemName from Dictionary group by itemName";
		return findByHQL(hql);
	}

	/**
	 *
	 * @param parentId 父节点的id
	 * @param leaf 是否需要渲染叶子节点
	 * @return
	 */
	public List<Dictionary> getByParent(Long parentId, boolean leaf) {
		String hql = "from Dictionary d where d.parentId=? and d.leaf=0";
		if (leaf) {
			hql = "from Dictionary d where d.parentId=? and d.leaf=1";
		}

		return findByHQL(hql, parentId);
	}

	/**
	 * 根据parentId查询所有的子级非叶子节点 并返回 按照itemName分组的结果
	 * 
	 * @param parentId
	 */
	public void findByParentId(Long parentId, List<Dictionary> resultList) {
		String hql = "from Dictionary d where d.parentId=?";
		// 1.根据父节点查询该父节点的子节点中拥有子级的节点
		List<Dictionary> dicList = findByHQL(hql, parentId);
		for (Dictionary dict : dicList) {
			if (dict.getLeaf() == 1) {
				resultList.add(dict);
			} else {
				findByParentId(dict.getDicId(), resultList);
			}
		}
	}


}
